﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Models;
using WorkflowDesign;
using Utilities;
using System.Web.Script.Serialization;
using BLL;

namespace WorkflowDesign.Controllers
{
    public class WorkflowController : Controller
    {
        public ViewResult Index()
        {
            return View(CH.GetAllData<Workflow>());
        }

        public ViewResult Details(int id)
        {
            return View();
        }

        public ActionResult Create()
        {
            return View();
        }

        public ActionResult Design(int? id)
        {
            return View(id);
        }



        public JsonResult DesignJson(int? targetid)
        {
            var wf = CH.GetAllData<Workflow>(w => w.ID == targetid, "Fields", "Conditions","Participants","Activities","ActivityResults").FirstOrDefault();
            wf.Activities = wf.Activities.OrderBy(a=>a.Sequence).ToList();
            wf.Fields = wf.Fields.OrderBy(f => f.Sequence).ToList();
            return new DataJsonResult<Workflow>() { Data = wf };
        }

        [HttpPost]
        public ActionResult Create(Workflow workflow)
        {
            if (ModelState.IsValid)
            {
                CH.Create<Workflow>(workflow);
                return RedirectToAction("Index");
            }

            return View(workflow);
        }

        public ActionResult Edit(int id)
        {
            return View(CH.GetDataById<Workflow>(id));
        }

        [HttpPost]
        public ActionResult Edit(Workflow workflow)
        {
            if (ModelState.IsValid)
            {
                CH.Edit<Workflow>(workflow);
                return RedirectToAction("Index");
            }
            return View(workflow);
        }

        [HttpPost]
        public ActionResult SaveProcess(Workflow workflow)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var wfdb = CH.DB.Workflows
                        .Include("Fields")
                        .Include("Conditions")
                        .Include("Participants")
                        .Include("Activities")
                        .Where(w => w.ID == workflow.ID).Single();

                    #region update Field
                    var fieldsdb = CH.GetAllData<Field>(f => f.WorkflowID == workflow.ID);
                    CH.EditCollection<Field>(fieldsdb, workflow.Fields);
                    #endregion

                    #region update Condition
                    if (workflow.Conditions == null)
                    {
                        wfdb.Conditions.Clear();
                    }
                    else
                    {
                        var conditionsdb = CH.GetAllData<Condition>(c => c.WorkflowID == workflow.ID, "Field");
                        workflow.Conditions.ForEach(c =>
                        {
                            c.Field = CH.DB.Fields.Single(f => f.FieldName == c.Field.FieldName);
                            c.FieldID = c.Field.ID;
                        });
                        CH.EditCollection<Condition>(conditionsdb, workflow.Conditions);
                    }
                    #endregion

                    #region update participants
                    if (workflow.Participants == null)
                    {
                        wfdb.Participants.Clear();
                    }
                    else
                    {
                        var participantsdb = CH.GetAllData<Participant>(c => c.WorkflowID == workflow.ID, "Conditions", "Employees");
                        if (workflow.Participants != null)
                        {
                            workflow.Participants.ForEach(p =>
                            {
                                var clist = new List<Condition>();
                                var pdb = CH.DB.Participants.FirstOrDefault(pp => pp.Title == p.Title);
                                if (p.Conditions != null)
                                {
                                    p.Conditions.ForEach(c =>
                                    {
                                        var cdb = CH.DB.Conditions.FirstOrDefault(cc=>cc.ConditionName ==c.ConditionName);
                                        clist.Add(cdb);//避免加入重复

                                    });
                                    p.Conditions.Clear();
                                    p.Conditions.AddRange(clist);
                                    clist.Clear();
                                }

                                var elist = new List<Employee>();
                                p.Employees.ForEach(e =>
                                {
                                    var edb = CH.DB.Employees.Find(e.ID);
                                    elist.Add(edb);
                                });
                                p.Employees.Clear();
                                p.Employees.AddRange(elist);
                                elist.Clear();

                                if (pdb != null)
                                {
                                    CH.DB.Entry(pdb).Collection("Conditions").CurrentValue = p.Conditions;
                                    CH.DB.Entry(pdb).Collection("Employees").CurrentValue = p.Employees;
                                }
                            });
                        }
                        CH.EditCollection<Participant>(participantsdb, workflow.Participants);
                    }
                    #endregion

                    #region update Activity
                    if (workflow.Activities == null)
                    {
                        wfdb.Activities.Clear();
                    }
                    else
                    {
                        var activitiesdb = CH.GetAllData<Activity>(c => c.WorkflowID == workflow.ID, "Participants");
                        if (workflow.Activities != null)
                        {
                            workflow.Activities.ForEach(a =>
                            {
                                if (a.Participants!=null)
                                {
                                    var plist = new List<Participant>();
                                    var adb = CH.DB.Activities.Include("Participants").FirstOrDefault(aa => aa.ActivityName == a.ActivityName);
                                      

                                    a.Participants.ForEach(c =>
                                    {
                                        var pdb = CH.DB.Participants.Find(c.ID);
                                        plist.Add(pdb);//避免加入重复

                                    });
                                    a.Participants.Clear();
                                    a.Participants.AddRange(plist);
                                    plist.Clear();

                                    if (adb != null)
                                        CH.DB.Entry(adb).Collection("Participants").CurrentValue = a.Participants;
                                }

                                if (a.ActivityResults != null)
                                {
                                    var alist = new List<ActivityResult>();
                                    var adb = CH.DB.Activities.Include("ActivityResults").FirstOrDefault(aa => aa.ActivityName == a.ActivityName);

                                    a.ActivityResults.ForEach(c =>
                                    {
                                        var pdb = CH.DB.ActivityResults.Find(c.ID);
                                        alist.Add(pdb);//避免加入重复

                                    });
                                    a.ActivityResults.Clear();
                                    a.ActivityResults.AddRange(alist);
                                    alist.Clear();

                                    if (adb != null)
                                        CH.DB.Entry(adb).Collection("ActivityResults").CurrentValue = a.ActivityResults;
                                }
                            });
                        }
                        CH.EditCollection<Activity>(activitiesdb, workflow.Activities);
                    }
                    #endregion

                    #region update ActivityResult
                    if (workflow.ActivityResults == null)
                    {
                        wfdb.ActivityResults.Clear();
                    }
                    else
                    {
                        var activityresultdb = CH.GetAllData<ActivityResult>(c => c.WorkflowID == workflow.ID,"Activity");
                        if (workflow.ActivityResults != null)
                        {
                            workflow.ActivityResults.ForEach(a =>
                            {
                                if (a.Activity != null)
                                {
                                    a.Activity = CH.DB.Activities.Single(i => i.ActivityName == a.Activity.ActivityName);
                                }
                            });
                        }
                        CH.EditCollection<ActivityResult>(activityresultdb, workflow.ActivityResults);
                    }
                    #endregion

                }
                catch (Exception e)
                {

                }
                return Json(1);
            }
            else
            {
                var error = ModelState.Values.ToList().FindAll(err => err.Errors.Count > 0);
            }
            return View(workflow);
        }

        public JsonResult GetActivityResultsJson(int targetid)
        {
            var data = CH.GetAllData<ActivityResult>(i=>i.ActivityID == targetid);
            return new DataJsonResult<ActivityResult>() { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = data };
        }

        public JsonResult PeopleFinder(string condition)
        {
            List<Employee> data;
            if (condition == "all")
                data = CH.GetAllData<Employee>();
            else
            {
                data = CH.GetAllData<Employee>(item => item.FullName.Contains(condition.Trim()));

            }

            return new DataJsonResult<Employee>() { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = data };
        }

        public ActionResult Delete(int id)
        {
            return View(CH.GetDataById<Workflow>(id));
        }

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            CH.Delete<Workflow>(id);
            return RedirectToAction("Index");
        }
    }
}